from django.shortcuts import render_to_response
from django.http import  HttpResponse
from django.template import RequestContext
from django.contrib.auth.models import User
from regist.models import Restaurant
from common.json import packIntoJsonData
from django.contrib import auth
from common.error import commonResponse
from exportmodels import exportrestaurant

# Create your views here. 
def quickRegist(request):
    return render_to_response('regist/fastRegist.html', context_instance=RequestContext(request))

def registcommit(request):
    user = request.POST['username']
    password = request.POST['password']
    email    = request.POST['email']
    
    
    Result = commonResponse()
    
    queueObj = User.objects.filter( username__exact= user )
    
    if queueObj.count() > 0: #first check if has a same name's user
        Result.result = 1
    
    else:    
        newuser = User.objects.create_user( user,email,password )
       
        if newuser is not None:
            newuser.save()
            Result.result = 0
            
        else:
            Result.result = -1
        
    return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")


def restaurantregistcommit(request):
    Result = commonResponse()
    
    if not request.user.is_authenticated(): 
        Result.setcommonError(4); # no login error
        return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")
    
    restaurantname = request.POST['restaurantname']
    if 'anothername' in request.POST:
        anothername = request.POST['anothername']
    else:
        anothername = None
    tastestyle    = request.POST['tastestyle']
    address       = request.POST['address']
    
    if 'nearby' in request.POST:
        nearby = request.POST['nearby']
    else:
        nearby = None
    #gpsposition_x = request.POST['gpsposition_x']
    if 'gpsposition_x' in request.POST:
        gpsposition_x = request.POST['gpsposition_x']
    else:
        gpsposition_x = None
    #GpsPosition_y = request.POST['gpsposition_y']
    
    if 'gpsposition_y' in request.POST:
        gpsposition_y = request.POST['gpsposition_y']
    else:
        gpsposition_y = None
    
    
    phone1 = request.POST['phone1']
    if 'phone2' in request.POST:
        phone2 = request.POST['phone2']
    else:
        phone2 = None    
    
    timertoopen = request.POST['open']
    timertoclose = request.POST['close']
    if 'howtogetthere' in request.POST:
        howtogetthere = request.POST['howtogetthere']    
    else:
        howtogetthere = None    
    
    administrator = request.user.username   
    
    
    #queueObj = Restaurant.objects.filter( username__exact= user )
    
    #if queueObj.count() > 0: #first check if has a same name's user
    #   Result.result = 1
    
    #else:    
    if 1:
        newres = Restaurant(
                              name = restaurantname, 
                              anothername = anothername, 
                              tastestyle= tastestyle, 
                              address = address, 
                              nearby = nearby, 
                              phone1 = phone1, 
                              phone2 = phone2, 
                              gpsposition_x=gpsposition_x,
                              gpsposition_y=gpsposition_y,
                              timertoopen = timertoopen, 
                              timertoclose = timertoclose, 
                              howtogetthere = howtogetthere, 
                              administrator = administrator,
                              queuestartflag = False,
                              queuenextcallnum = 0,
                              queuenextdistributenum = 0
                              )
       
        if newres is not None:
            newres.save()
            Result.result = 0
             
        else:
            Result.result = -1
        
    return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")

def login(request):
    return render_to_response('regist/login.html', context_instance=RequestContext(request))

def logincheck(request):  
    username = request.POST['username']   
    password = request.POST['password']  
    user = auth.authenticate(username=username, password=password)
    
    loginResult = commonResponse()
    
    if user is not None and user.is_active: 
        # Correct password, and the user is marked "active"      
        auth.login(request, user)   
        # Redirect to a success page.   
        loginResult.result = 0;
        
    else:   
        # Show an error page   
        queueObj = User.objects.filter( username__exact= user )
    
        if queueObj.count() > 0: #first check if has a same name's user
            loginResult.result = 3 #password error
        else:
            loginResult.result = 2 #no user
        
    return HttpResponse(packIntoJsonData( loginResult ),mimetype="text/json")    
    
def logout(request):   
    auth.logout(request)
    # Redirect to a success page. 
    return HttpResponse(packIntoJsonData(  commonResponse() ),mimetype="text/json")
            

def getrestaurantinfo( request ):   
    Result = commonResponse() 
    if request.user.is_authenticated():
        res = Restaurant.objects.filter(administrator =  request.user.username)
        if not res  :
            
            Result.setcommonError(6); # restaurant record not exist
            return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")
        else:
            Result.setcommonError(0);
            Result.setuserdata( exportrestaurant(res[0]))
            return HttpResponse(packIntoJsonData( Result),mimetype="text/json")
    else:
        
        Result.setcommonError(4) #user hasn't login
        return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")
        
def updaterestaurantinfo( request ):    
    
    Result = commonResponse()
    
    if not request.user.is_authenticated(): 
        Result.setcommonError(4); # no login error
        return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")    
    else:        
        res = Restaurant.objects.get(administrator =  request.user.username)
        if res is None :
            Result = commonResponse()
            Result.setcommonError(6); # restaurant record not exist
            return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")
        else:
            res.restaurantname = request.POST['restaurantname']
            if 'anothername' in request.POST:
                res.anothername = request.POST['anothername']
            else:
                res.anothername = None
            res.tastestyle    = request.POST['tastestyle']
            res.address       = request.POST['address']
            
            if 'nearby' in request.POST:
                res.nearby = request.POST['nearby']
            else:
                res.nearby = None
            #gpsposition_x = request.POST['gpsposition_x']
            if 'gpsposition_x' in request.POST:
                res.gpsposition_x = request.POST['gpsposition_x']
            else:
                res.gpsposition_x = None
            #GpsPosition_y = request.POST['gpsposition_y']
            
            if 'gpsposition_y' in request.POST:
                res.gpsposition_y = request.POST['gpsposition_y']
            else:
                res.gpsposition_y = None
            
            
            res.phone1 = request.POST['phone1']
            if 'phone2' in request.POST:
                res.phone2 = request.POST['phone2']
            else:
                res.phone2 = None    
            
            res.timertoopen = request.POST['open']
            res.timertoclose = request.POST['close']
            if 'howtogetthere' in request.POST:
                res.howtogetthere = request.POST['howtogetthere']    
            else:
                res.howtogetthere = None    
            res.save()
            Result.result = 0
            return HttpResponse(packIntoJsonData( Result ),mimetype="text/json")

    